package com.zlx.store.goods.job;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zlx.store.domain.entity.Order;
import com.zlx.store.domain.entity.OrderRelateGoods;
import com.zlx.store.goods.dao.OrderDao;
import com.zlx.store.goods.dao.OrderRelateGoodsDao;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.quartz.QuartzJobBean;

import java.time.LocalDateTime;
import java.util.*;

/**
 * 自动化热销商品
 */
@Slf4j
public class HotGoodsJob extends QuartzJobBean {
    @Autowired
    private OrderDao orderDao;
    @Autowired
    private OrderRelateGoodsDao orgd;
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        //删除前一天的hotGoods
        redisTemplate.delete("hotGoods_auto");
        //查询7天内未取消订单
        LambdaQueryWrapper<Order> wrapper=new LambdaQueryWrapper<>();
        Date sevenDaysAgo = new Date(System.currentTimeMillis() - 7 * 24 * 60 * 60 * 1000);
        wrapper.between(Order::getOrderCreateTime,sevenDaysAgo,new Date());
        wrapper.ne(Order::getOrderState,4);
        List<Order> orders=orderDao.selectList(wrapper);
        //统计7天内各商品销售额
        HashMap<Long,Integer> sales=new HashMap<>();
        orders.forEach(order -> {
            LambdaQueryWrapper<OrderRelateGoods> relateWrapper=new LambdaQueryWrapper<>();
            relateWrapper.eq(OrderRelateGoods::getOrderId,order.getOrderId());
            List<OrderRelateGoods> orderRelateGoods=orgd.selectList(relateWrapper);
            orderRelateGoods.forEach(good->{
                Long id=good.getGoodsId();
                Integer count=good.getGoodsCount();
                sales.merge(id,count,Integer::sum);
//                if (sales.containsKey(id)){
//                    Integer oldCount=sales.get(id);
//                    sales.put(id,count+oldCount);
//                }
//                else {
//                    sales.put(id,count);
//                }
            });});
        // 将商品信息存入redis
        sales.forEach((id, count) -> {
            redisTemplate.opsForZSet().add("hotGoods_auto", id, count);
        });
        // 修改hotGoods_manual的7天销量,从hotGoods_auto里移除
        Set<Object> hotGoodsSet = redisTemplate.opsForZSet().range("hotGoods_manual", 0, -1);
        for (Object hotGoods : hotGoodsSet) {
            Long id = Long.parseLong(hotGoods.toString());
            if (Objects.nonNull(redisTemplate.opsForZSet().score("hotGoods_auto", id))) {
                redisTemplate.opsForZSet().remove("hotGoods_auto", id);
                redisTemplate.opsForZSet().add("hotGoods_manual", id, sales.get(id));
            }
        }
    }
}
